package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.product.domain.ProductUnit;
import com.spzx.product.mapper.ProductUnitMapper;
import com.spzx.product.service.ProductUnitService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

@Service
public class ProductUnitServiceImpl extends ServiceImpl<ProductUnitMapper, ProductUnit> implements ProductUnitService {
    @Override
    public Page<ProductUnit> selectUnitPage(ProductUnit productUnit) {

        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");

        Page<ProductUnit> page = new Page<>(StringUtils.isEmpty(pageNum) ? 1 : Integer.parseInt(pageNum)
                , StringUtils.isEmpty(pageSize) ? 3 : Integer.parseInt(pageSize));

        LambdaQueryWrapper<ProductUnit> lambdaQuery = Wrappers.lambdaQuery(ProductUnit.class);
        String name = productUnit.getName();
        if (!StringUtils.isEmpty(name)) {
            lambdaQuery.like(ProductUnit::getName, name);
        }
        this.page(page, lambdaQuery);
        return page;
    }

    @Override
    public boolean checkUnitNameUnique(ProductUnit productUnit) {
        // 1 判断新增还是更新   id不为空  表示 更新        id  为空 表示新增

        Long id = productUnit.getId() == null ? -1L : productUnit.getId();
        ProductUnit selectProductUnit =this.getOne(Wrappers.lambdaQuery(ProductUnit.class)
                .eq(ProductUnit::getName, productUnit.getName()));
        if (selectProductUnit!=null && id.longValue()!=selectProductUnit.getId().longValue()){
            return false ;
        }
            return true;
    }

}
